package com.akk.platform.manage;



import com.akk.module.avs.entity.AvsLecturer;
import com.akk.module.avs.model.request.AvsLectureRequest;
import com.akk.module.avs.service.AvsLectureService;
import com.akk.module.upload.service.PictureService;
import com.akk.module.upload.utils.FtpUtil;
import com.akk.utils.*;
import com.akk.utils.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/platform/manage/lecture/")
public class LectureAction {

    Logger logger = LoggerFactory.getLogger(LectureAction.class);

    @Value("${ftp.address}")
    private String FTP_ADDRESS;
    @Value("${ftp.port}")
    private Integer FTP_PORT;
    @Value("${ftp.username}")
    private String FTP_USERNAME;
    @Value("${ftp.password}")
    private String FTP_PASSWORD;
    @Value("${ftp.base.path}")
    private String FTP_BASE_PATH;
    @Value("${image.base.url}")
    private String IMAGE_BASE_URL;

    @Autowired
    private AvsLectureService lectureService;

    @Autowired
    private PictureService pictureServices;


    @GetMapping(value = "/query")
    public RestResponse query(@RequestParam String ct){
        int type = 1;
        if (PatternUtil.isIdCard(ct))
            type = 0;
        AvsLecturer entity = lectureService.queryByCertificateNumberAndType(ct, type);
        if (entity == null){
            return RestResponse.build("1","未查询到信息");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = format.format(entity.getStartTime());
        String endTime = format.format(entity.getEndTime());
        if (startTime.length() > 10)
            startTime = startTime.substring(0,10);
        if (endTime.length()>10)
            endTime = endTime.substring(0,10);
        entity.setExpiryDate(startTime + " - " + endTime);
        if (entity == null)
            return RestResponse.build("1","未查询到信息");
        return RestResponse.build(entity);
    }

    @GetMapping(value = "/list")
    @RequiresPermissions("sys:lecture:list")
    public RestResponse list(@Valid Query query, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage());
        PageHelper.startPage(query.getPage(),query.getLimit());
        Map params = query.getSearch();
        List<AvsLecturer> list = lectureService.queryByParams(params);
        for (AvsLecturer entity:list) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String startTime = format.format(entity.getStartTime());
            String endTime = format.format(entity.getEndTime());
            entity.setExpiryDate(startTime+" - "+endTime);
        }
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    @PostMapping(value = "/del")
    @RequiresPermissions("sys:lecture:delete")
    public RestResponse del(@RequestBody AvsLectureRequest request){
        if (request.getId() == null || request.getId() == 0)
            return RestResponse.build("1","参数缺失");
        String fileUrl = request.getFileUrl();
        if (fileUrl != null && fileUrl.length() > 1)
        {
            fileUrl = fileUrl.substring(fileUrl.indexOf("/picture/")+1,fileUrl.length());
            boolean remove1 = FtpUtil.removeFile(FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD,fileUrl);
            if (!remove1){
                logger.error("照片文件删除失败:"+fileUrl);
                System.out.println("照片文件删除失败");
            }
        }
        String photoUrl = request.getPhotoUrl();
        if (photoUrl != null && photoUrl.length() > 1){
            photoUrl = photoUrl.substring(photoUrl.indexOf("/picture/")+1,photoUrl.length());
            boolean remove1 = FtpUtil.removeFile(FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD,photoUrl);
            if (!remove1){
                logger.error("照片文件删除失败:"+photoUrl);
                System.out.println("证书文件删除失败");
            }
        }
        lectureService.del(request.getId());
        return RestResponse.build("success");
    }

    @PostMapping(value = "/update")
    @RequiresPermissions("sys:lecture:update")
    public RestResponse update(AvsLectureRequest request) throws ParseException {
        String expiryDate = request.getExpiryDate();
        String startTime = expiryDate.substring(0,10);
        String endTime = expiryDate.substring(13,expiryDate.length());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);
        String company = request.getCompany();
        String photoUrl;
        AvsLecturer lecturerEntity = lectureService.queryById(request.getId());
        if (request.getPhoto() != null ){
            // http://192.168.1.179/picture/2017/06/16/1497583666536132.png
            String photoFile = lecturerEntity.getPhotoUrl().substring(lecturerEntity.getPhotoUrl().indexOf("/picture/"),lecturerEntity.getPhotoUrl().length());
            photoFile = photoFile.substring(1,photoFile.length());
            boolean remove1 = FtpUtil.removeFile(FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD,photoFile);
            if (!remove1)
                System.out.println("照片文件删除失败:"+photoFile);
            if (lecturerEntity.getFileUrl() != null && lecturerEntity.getFileUrl().length() > 1) {
                String ctFile = lecturerEntity.getFileUrl().substring(lecturerEntity.getFileUrl().indexOf("/picture/"), lecturerEntity.getFileUrl().length());
                ctFile = ctFile.substring(1,ctFile.length());
                boolean remove2 = FtpUtil.removeFile(FTP_ADDRESS,FTP_PORT,FTP_USERNAME,FTP_PASSWORD,ctFile);
                if (!remove2)
                    logger.error("证书文件删除失败:"+ctFile);
            }
            Map<String,Object> map = pictureServices.uploadPicture(request.getPhoto());
            if (map.get("status").toString().equals("1"))
                return RestResponse.build("1","照片上传失败");
            else{
                photoUrl = map.get("url").toString();
                lecturerEntity.setPhotoUrl(photoUrl);
            }
        }
        lecturerEntity.setCertificateNumber(request.getCertificateNumber());
        lecturerEntity.setName(request.getName());
        lecturerEntity.setStartTime(startDate);
        lecturerEntity.setEndTime(endDate);
        lecturerEntity.setIdCard(request.getIdCard());
        lecturerEntity.setFileUrl(null);
        lecturerEntity.setCompany(company);
        lecturerEntity.setType(request.getType());
        lectureService.update(lecturerEntity);
        return RestResponse.build("200","操作成功");
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @RequiresPermissions("sys:lecture:add")
    public RestResponse add(AvsLectureRequest lectureRequest) throws ParseException {
        if (lectureRequest.getPhoto() == null){
            return RestResponse.build("1","请上传照片");
        }
        Map<String,Object> map = pictureServices.uploadPicture(lectureRequest.getPhoto());
        if (map.get("status").toString().equals("1"))
            throw new BusinessException("照片上传失败");
        String expiryDate = lectureRequest.getExpiryDate();
        String startTime = expiryDate.substring(0,10);
        String endTime = expiryDate.substring(13,expiryDate.length());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);
        AvsLecturer entity = new AvsLecturer();
        entity.setPhotoUrl(map.get("url").toString());
        entity.setCertificateNumber(lectureRequest.getCertificateNumber());
        entity.setCompany(lectureRequest.getCompany());
        entity.setEndTime(endDate);
        entity.setStartTime(startDate);
        entity.setIdCard(lectureRequest.getIdCard());
        entity.setCreateDate(new Date());
        entity.setName(lectureRequest.getName());
        entity.setType(lectureRequest.getType());
        lectureService.save(entity);
        return RestResponse.build("success");
    }

    @GetMapping(value = "/info")
    @RequiresPermissions("sys:lecture:info")
    public RestResponse info(@RequestParam Long id){
        AvsLecturer entity = lectureService.queryById(id);
        entity.setExpiryDate(entity.getStartTime().toString().substring(0,9)+" - "+entity.getEndTime().toString().substring(0,9));
        return RestResponse.build(entity);
    }
}
